// 计数器：判断线程池的任务是否已经全部执行完

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CountDownLatchDemo2 {
    // 创建计数器
    private static CountDownLatch countDownLatch = new CountDownLatch(5);

    public static void main(String[] args) throws InterruptedException {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    Thread currThread = Thread.currentThread();
                    System.out.println(currThread.getName() + "开始执行");
                    // 线程执行所用时间
                    int runTime = (1 + new Random().nextInt(5));
                    try {
                        TimeUnit.SECONDS.sleep(runTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(currThread.getName() + "执行完成，用时" + runTime);
                    //计数器-1
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await(); // 阻塞等待，直到所有线程执行完
        System.out.println("执行结果");
    }
}
